package com.pizza.control;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;

/**
 * Class LoginNavigationManager
 *
 */
public class LoginNavigationManager extends NavigationHandler
{
	public static final String RETURN_BACK = "!returnBack";

	public static final String LOGIN_GLOBAL = "identification";

	NavigationHandler _base;

	String actionNameCurrent;

	String actionMethodCurrent;

	public LoginNavigationManager(NavigationHandler base)
	{
		super();
		_base = base;
	}

	public void handleNavigation(FacesContext context, String fromAction, String outcome)
	{
		if (fromAction != null && outcome != null)
		{
			System.out.println("DEBUG: handleNavigation: " + fromAction + " " + outcome);
			actionNameCurrent = fromAction;
			actionMethodCurrent = outcome;

			ClientBean loginManager = (ClientBean) context.getExternalContext()
					.getSessionMap().get("clientBean");

			if (actionMethodCurrent != null)
				if (actionMethodCurrent.equals(RETURN_BACK))
					navigationCase4ReturningBack(context, loginManager);

			if (actionNameCurrent.equals("#{commandeBean.validerEtape1}")
					&& actionMethodCurrent.equals("validpanier"))
				navigationCase4Login(context, loginManager);

			_base.handleNavigation(context, actionNameCurrent, actionMethodCurrent);
		}
	}

	private void navigationCase4Login(FacesContext fc, ClientBean loginManager)
	{
		boolean loginStatus = loginManager.isConnected();

		if (!loginStatus && actionNameCurrent != null
				&& !actionNameCurrent.equals(LOGIN_GLOBAL))
		{
			loginManager.setPreviousAction(actionNameCurrent);
			loginManager.setPreviousMethod(actionMethodCurrent);
			loginManager.setPreviousViewId(fc.getViewRoot().getViewId());
			loginManager.setReturnRequired(true);

			actionNameCurrent = LOGIN_GLOBAL;
			actionMethodCurrent = LOGIN_GLOBAL;
		}
	}

	private void navigationCase4ReturningBack(FacesContext fc, ClientBean loginManager)
	{
		if (loginManager.isConnected())
		{
			actionNameCurrent = loginManager.getPreviousAction();
			actionMethodCurrent = loginManager.getPreviousMethod();
			fc.getViewRoot().setViewId(loginManager.getPreviousViewId());
			loginManager.setReturnRequired(false);
		}
	}
}
